var ToolRepairApprovalTableInit = function () {
    var oTableInit = {};
    //初始化Table
    oTableInit.Init = function () {
        $('#toolRepairApprovalTable').bootstrapTable({
            url: ctx + '/tool/repairApproval/findToolRepairApprovalListByPage/get.mvc',         //请求后台的URL（*）
            method: 'get',                      //请求方式（*）
//            toolbar: '#toolbar',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true,                   //是否显示分页（*）
            paginationLoop: false,
            sortable: true,                     //是否启用排序
            sortOrder: "asc",                   //排序方式
            queryParams: oTableInit.queryParams,//传递参数（*）
            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1,                       //初始化加载第一页，默认第一页
            pageSize: 10,                       //每页的记录行数（*）
            pageList: [10, 25, 50, 100],        //可供选择的每页的行数（*）
            search: false,                       //是否显示表格搜索，此搜索是客户端搜索，不会进服务端，所以，个人感觉意义不大
            strictSearch: true,
            showColumns: false,                  //是否显示所有的列
            showRefresh: false,                  //是否显示刷新按钮
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            height: 500,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
            uniqueId: "pkId",                     //每一行的唯一标识，一般为主键列
            showToggle: false,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            singleSelect: false,                    //禁止多选
            checkboxHeader: true,                 //列头取消多选
            columns: [
                {
                    radio: true,
                    align: 'center',
                    valign: 'middle'
                },
                {
                    title: '序号',
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        var options = $('#toolRepairApprovalTable').bootstrapTable('getOptions');
                        return options.pageSize * (options.pageNumber - 1) + index + 1;
                    }
                }, {
                    field: 'status',
                    title: '审批状态',
                    sortable: false,
                    align: 'center',
                    valign: 'middle',
                    formatter: function (value, row, index) {
                        if (value === '1') {
                            return '待审批'
                        } else if (value === '0') {
                            return "审批完成"
                        } else {
                            return value
                        }
                    }
                }, {
                    field: 'toolCode',
                    title: '工装编码',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'toolName',
                    title: '工装名称',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'toolModel',
                    title: '工装规格',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'toolTypeValue',
                    title: '工装类别',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'
                }, {
                    field: 'equipName',
                    title: '所属设备',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'applicationDate',
                    title: '申请时间',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'requiredDate',
                    title: '需求时间',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'sendRepairUser',
                    title: '送修人',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'repairRequirement',
                    title: '维修要求',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, /*{
                    field: 'sendRepairCompany',
                    title: '送修公司',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'contact',
                    title: '联系人',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, {
                    field: 'contactNumber',
                    title: '联系方式',
                    sortable: false,
                    align: 'center',
                    valign: 'middle'

                }, */{
                    field: 'pkId',
                    title: 'pkId',
                    visible: false
                },{
                    field: 'repairId',
                    title: 'repairId',
                    visible: false
                }]

        });
    };
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        return {   // 这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            size: params.limit,   // 页面大小
            num: (params.offset / params.limit) + 1,  // 页码
            sort: params.sort,
            order: params.order,
            areaId: $("#areaCode").val(),
            shopId: $("#shopCode").val(),
            lineId: $("#lineCode").val(),
            equipCode: $("#equipCode").find("option:selected").text(),
            applicationStartDate: $("#applicationStartDate").val(),
            applicationEndDate: $("#applicationEndDate").val()
        }
    };
    return oTableInit;
};

jQuery(document).ready(function () {
    //1.初始化Table
    var oTable = new ToolRepairApprovalTableInit();
    oTable.Init();
    //初始化页面
    toolRepairApprovalInit.init();
});


var toolRepairApprovalInit = function () {
    return {
        init: function () {
            toolRepairApprovalInit._query();
            toolRepairApprovalInit._keyQuery();
            toolRepairApprovalInit._reset();
            toolRepairApprovalInit._refresh();
            toolRepairApprovalInit._commit();
            toolRepairApprovalInit._initShopSelect();
            toolRepairApprovalInit._initAreaSelect();
            toolRepairApprovalInit._initLineSelect();
            toolRepairApprovalInit._initEquipCodeSelect2();
            toolRepairApprovalInit._initDateControl();
        },
        //条件查询
        _query: function () {
            $("#queryRepairApproval").on("click", function () {
                $('#toolRepairApprovalTable').bootstrapTable('refreshOptions', {
                    pageNumber: 1
                });
            });
        },
        //按键查询
        _keyQuery: function () {
            $(".repair-approval-search").keypress(function (e) {
                if (e.which === 13) {
                    $("#queryRepairApproval").trigger("click");
                }
            });
        },
        //重置查询
        _reset: function () {
            $(".reset").on("click", function () {
                $(".clearfix input").val("");
                $(".clearfix select").val("");
                $("#equipCode").val(null).trigger("change");
                //$("#dutyUser").val(null).trigger("change");
            });
        },
        _refresh: function () {
            //刷新
            $("#refreshTable").on("click", function () {
                $('#toolRepairApprovalTable').bootstrapTable('refresh');
            });
        },
        _initDateControl: function () {
            $('.form-datetime').datetimepicker({
                format: 'yyyy-mm-dd hh:ii:ss',
                language: 'zh-CN',
                autoclose: true,
                pickerPosition: "bottom-left",
                //endDate : new Date(),
                forceParse: true
            }).on('hide', function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
            $('.form-datetime-day').datetimepicker({
                format: 'yyyy-mm-dd',
                minView: 2,
                autoclose: true,
                language: 'zh-CN',
                pickerPosition: "bottom-left",
                //endDate : new Date(),
                forceParse: true
            }).on('hide', function (event) {
                event.preventDefault();
                event.stopPropagation();
            });
        },
        //维修
        _commit: function () {
            $("#update").on('click', function (e) {
                e.preventDefault();
                var pkId = $.map($('#toolRepairApprovalTable').bootstrapTable('getSelections'), function (row) {
                    return row.pkId;
                });
                var repairId = $.map($('#toolRepairApprovalTable').bootstrapTable('getSelections'), function (row) {
                    return row.repairId;
                });
                if (pkId.length !== 1) {
                    DialogUtil.warning("请选择一行记录进行操作");
                    return false;
                }
                DialogUtil.ok_and_cancel("是否审批完成？", function () {
                    $.ajax({
                        url: ctx + '/tool/repair/approvalCompletion/save.mvc',
                        type: "post",
                        dataType: 'json',
                        data: {
                            approvalId: pkId.toString(),
                            repairId :repairId.toString()
                        },
                        success: function (response) {
                            console.log(response);
                            if (response.result === true) {
                                DialogUtil.ok("操作成功");
                                $('#toolRepairApprovalTable').bootstrapTable('refresh');
                            } else {
                                DialogUtil.error(response.message);
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            DialogUtil.error(errorThrown);
                        }
                    });
                }, function () {

                });
            });
        },
        _initLineSelect : function () {
            $.ajax({
                url: ctx +'/factory/product/listAllProduct/get.mvc',
                type:"post",
                aysnc: false,
                dataType:'json',
                data : '',
                success : function(data){
                    $("#lineCode").append("<option value=''>请选择</option>");
                    for (var i = 0; i < data.length; i++) {
                        $("#lineCode").append("<option value='"+data[i].pkId+"' >" + data[i].lineName + "</option>");
                    }
                },
                error: function(){
                    alert("系统错误");
                }
            });
        },
        _initShopSelect : function () {
            $.ajax({
                url: ctx +'/factory/shop/listAllShopsByFactoryId/get.mvc',
                type:"post",
                aysnc: false,
                dataType:'json',
                success : function(response){
                    if(response.result === true) {
                        var _data = response.data;
                        $("#shopCode").append("<option value='' >请选择</option>");
                        for (var i = 0; i < _data.length; i++) {
                            $("#shopCode").append("<option value='"+_data[i].pkId+"' >" + _data[i].shopName + "</option>");
                        }
                    } else {
                        DialogUtil.error(response.message);
                    }

                },
                error: function(){
                    alert("系统错误2");
                }
            });
        },
        _initAreaSelect : function () {
            $.ajax({
                url: ctx +'/factory/area/listAllArea/get.mvc',
                type:"post",
                aysnc: false,
                dataType:'json',
                data : '',
                success : function(response){
                    if(response.result === true) {
                        var _data = response.data;
                        $("#areaCode").append("<option value='' >请选择</option>");
                        for (var i = 0; i < _data.length; i++) {
                            $("#areaCode").append("<option value='"+_data[i].pkId+"' >" + _data[i].areaName + "</option>");
                        }
                    } else {
                        DialogUtil.error(response.message);
                    }
                },
                error: function(){
                    alert("系统错误");
                }
            });
        },
        _initEquipCodeSelect2 : function () {
            $('#equipCode').select2({
                ajax: {
                    url: ctx + '/measureTool/measureToolInfo/getEquipmentList/get.mvc',
                    dataType: 'json',
                    data: function (params) {
                        // Query parameters will be ?search=[term]&page=[page]
                        return {
                            search: params.term,
                            page: params.page || 1,
                            size: 10
                        };
                    },
                    processResults: function (response) {
                        // Tranforms the top-level key of the response object from 'items' to 'results'
                        var test = [];
                        if (response.data) {
                            var _data = response.data;
                            for (var int = 0; int < _data.length; int++) {
                                var obj = {};
                                obj.id = _data[int].pkId;
                                obj.text = _data[int].equipCode;
                                test.push(obj);
                            }
                        }
                        return {
                            results: test
                        };
                    },
                    // Additional AJAX parameters go here; see the end of this chapter for the full code of this example
                    cache: true

                },
                placeholder: '请选择',
                language: "zh-CN",
                escapeMarkup: function (markup) {
                    return markup;
                }, // let our custom formatter work
                minimumInputLength: 0
            });
        },
    }
}();